package edu.ucsb.cs56.W12.chatserver.view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

import edu.ucsb.cs56.W12.chatserver.controller.ServerController;

/**
 * ServerWindow class represent a JFrame window of a server
 * @author Peng Wang and Andro Stotts
 * @version 0.1
 */
public class ServerWindow extends JFrame{

	private static final long serialVersionUID = 1L;
	private JButton btStart;
	private JButton btClose;
	private TextArea taConsole;
	private static ServerWindow window;
	private ServerController controller;
	
	/**
	 * default constructor
	 */
	private ServerWindow(){
		btStart = new JButton("Start server");
		btClose = new JButton("Close server");
		taConsole = new TextArea();
		//get an instance of controller
		controller = ServerController.getController();
	}
	
	/**
	 * static method is used to get the ServerWindow object
	 * @return the ServerWindow object
	 */
	public static ServerWindow getWindow(){
		if(window == null)
			window = new ServerWindow();
		return window;
	}
	
	/**
	 * create the server window
	 */
	public void launchWindow(){
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setLocation(100, 100);
		this.setSize(800, 600);
		this.setTitle("Chatting Server");
		JPanel panel = new JPanel();
		panel.add(btStart);
		panel.add(btClose);
		this.add(panel, BorderLayout.NORTH);
		this.add(taConsole, BorderLayout.CENTER);
		btStart.addActionListener(new MyButtonListener());
		btClose.addActionListener(new MyButtonListener());
		this.setVisible(true);
		
		taConsole.setEditable(false);
		taConsole.setBackground(Color.WHITE);
	}
	
	/**
	 * get the TextArea component of the server window
	 * @return TextArea component that represents the server output console
	 */
	public TextArea getTaConsole(){
		return taConsole;
	}
		
	/**
	 * MyButtonListener handles the actions when buttons have been clicked on the server window
	 * @author Peng Wang and Andro Stotts
	 * @version 0.1
	 */
	class MyButtonListener implements ActionListener{
		/**
		 * actionPerformed is used to handle an ActionEvent
		 * @param e e is the action event
		 */
		public void actionPerformed(ActionEvent e) {
			if(e.getActionCommand() == "Start server"){
				taConsole.append(controller.startServer());	
			}
			else{
				taConsole.append(controller.closeServer());
			}
		}		
	}
}
